import fetch from 'isomorphic-fetch';
import cookie from 'js-cookie';

const errorMessages = (res) => `${res.status} ${res.statusText}`;

function check401(res) {
  if (res.status === 401) {
    location.href = '/401';
  }
  return res;
}

function check404(res) {
  if (res.status === 404) {
    return Promise.reject(errorMessages(res));
  }
  return res;
}

function jsonParse(res) {
  return res.json().then(jsonResult => ({ ...res, jsonResult }));
}

function errorMessageParse(res) {
  const { success, message } = res.jsonResult;
  if (!success) {
    return Promise.reject(message);
  }
  return res;
}

function toQueryString(obj) {
  return obj ? Object.keys(obj).sort().map(function (key) {
    var val = obj[key];
    if (Array.isArray(val)) {
      return val.sort().map(function (val2) {
        return encodeURIComponent(key) + '=' + encodeURIComponent(val2);
      }).join('&');
    }

    return encodeURIComponent(key) + '=' + encodeURIComponent(val);
  }).join('&') : '';
}

function xFetch(url, options) {

  const opts = { ...options };
  opts.headers = {
    ...opts.headers,
    // authorization: cookie.get('authorization') || '',
  };

  // url = 'http://192.168.248.58/' + url;
  url = '/' + url;

  // 允许跨域
  opts.mode = 'cors';

  return fetch(url, opts)
    .then(check401)
    .then(check404)
    .then(jsonParse);
}

function get(url) {
  return xFetch(url);
}

function post(url, data) {
  return xFetch(url, {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
    },
    body: toQueryString(data)
  });
}

function put() {
  console.log('this is put');
}

function del() {
  console.log('this is fetch del');
}

export {get, post, put, del};
